package com.gitee.jwds666.fs.utils;

import java.lang.reflect.Field;

public class ReflectUtils {

    /**
     * 设置属性
     * @param obj
     * @param fieldName
     * @param fieldValue
     */
    public static boolean setField(Object obj,String fieldName,String fieldValue){
        Class clz = obj.getClass();
        try {
            Field field = clz.getDeclaredField(fieldName);
            if (field==null){
                field = clz.getField(fieldName);
            }
            Class type = field.getType();
            Object val = null;
            if (type == byte.class){
                val = Byte.parseByte(fieldValue);
            }else if (type == boolean.class){
                val = Boolean.parseBoolean(fieldValue);
            }else if (type == short.class){
                val = Short.parseShort(fieldValue);
            }else if (type == int.class){
                val = Integer.parseInt(fieldValue);
            }else if (type == float.class){
                val = Float.parseFloat(fieldValue);
            }else if (type == long.class){
                val = Long.parseLong(fieldValue);
            }else if (type == double.class){
                val = Double.parseDouble(fieldValue);
            }else if (type == Byte.class){
                val = Byte.parseByte(fieldValue);
            }else if (type == Boolean.class){
                val = Boolean.parseBoolean(fieldValue);
            }else if (type == Short.class){
                val = Short.parseShort(fieldValue);
            }else if (type == Integer.class){
                val = Integer.parseInt(fieldValue);
            }else if (type == Float.class){
                val = Float.parseFloat(fieldValue);
            }else if (type == Long.class){
                val = Long.parseLong(fieldValue);
            }else if (type == Double.class){
                val = Double.parseDouble(fieldValue);
            }else if (type == String.class){
                val = fieldValue;
            }
            field.setAccessible(true);
            field.set(obj,val);
            return true;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 设置属性
     * @param obj
     * @param exp
     */
    public static boolean setField(Object obj,String exp){
        String [] strArr = exp.split("=");
        if (strArr.length ==2){
            return setField(obj,strArr[0].trim(),strArr[1].trim());
        }
        return false;
    }
}
